<?php

include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/graphics/BitmapDimensions.php';

class BitmapUtils
{
	private static $target;
	public static  $bitmapData;
	
	public static function resizeBitmap($filename, BitmapDimensions $dimensions)
	{	
		// Get new sizes
		list($width, $height, $type) = getimagesize($filename); 
		
		switch ($type)
		{
			case IMG_GIF:
				self::$bitmapData = imagecreatefromgif($filename);
				break;           
			                     
			case IMG_JPG:        
				self::$bitmapData = imagecreatefromjpeg($filename);
				break;           
			                     
			case IMG_JPEG:       
				self::$bitmapData = imagecreatefromjpeg($filename);
				break;
		}
		
		// constrain porportionally to width
		if (!$dimensions->height)
		{
			$newwidth  = $dimensions->width;
			$newheight = self::calculatePorportion($dimensions->width, $width, $height); //ceil($a1 / $a * $b);
		}
		// constrain porportionally to height
		else if (!$dimensions->width)
		{
			$newwidth  = self::calculatePorportion($dimensions->height, $height, $width); //ceil($a1 / $a * $b);
			$newheight = $dimensions->height;
		}
		else
		{
			$newwidth = $dimensions->width; 
			$newheight = $dimensions->height;
		}

		
		switch ($type)
		{
			case IMG_GIF:
				return self::resizeGIF($width, $height, $newwidth, $newheight);
				break;
			
			case IMG_JPG:
				return self::resizeJPG($width, $height, $newwidth, $newheight);
				break;
			
			case IMG_JPEG:
				return self::resizeJPG($width, $height, $newwidth, $newheight);
				break;
		}
		
	}
	
	public static function resizeGIF($width, $height, $newwidth, $newheight)
	{
		// Load 
		$resize = imagecreatetruecolor($newwidth, $newheight); 
		
		// Resize 
		imagecopyresampled ($resize, self::$bitmapData, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
		//imagecopyresized($resize, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
		
		return array("data"=>$resize, "type"=>IMG_GIF);
		
		// Output 
		//imagegif($resize, "output/".$filename);
	}
	
	public static function resizeJPG($width, $height, $newwidth, $newheight)
	{
		// Load 
		$resize = imagecreatetruecolor($newwidth, $newheight); 

		// Resize 
		imagecopyresampled ($resize, self::$bitmapData, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
		//imagecopyresized($resize, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 

		return array("data"=>$resize, "type"=>IMG_JPG);
		
		// Output 
		//imagejpeg($resize, "output/".$filename, 85);
	}
	
	private static function getCropDimension(BitmapDimensions $dimensions, $width, $height)
	{
		if (!$dimensions->height)
		{
			
		}
		
		
	}
	
	private static function calculatePorportion($a1, $a, $b)
	{
		return ceil($a1 / $a * $b);
	}
}
?>
